package com.gongyibao.gbase.mq.thread;

/**
 * @Author: 张启峰
 * @Date: 2023/4/17 14:48
 * @Description: gyb-
 */

import com.cvicse.inforsuitemq.InforsuiteMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

class MessagesThroughputRecver implements Runnable {
    private Thread t;

    private Destination destination;
    private String subject;
    private Session session;
    private String user = "admin";
    private String password = "admin";
    private String url = "failover:(tcp://192.168.6.55:8688)";
    private int ackMode = Session.AUTO_ACKNOWLEDGE;

    MessagesThroughputRecver(String sub, Session sess) {
        subject = sub;
        session = sess;
    }

    MessagesThroughputRecver() {
    }

    public void start() {
        t = new Thread(this);
        t.start();
    }

    public void run() {
        try {
            destination = session.createQueue(subject);
            MessageConsumer consumer = null;
            consumer = session.createConsumer(destination);
            consumeMessagesAndClose(consumer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void consumeMessagesAndClose(MessageConsumer consumer) throws JMSException, IOException {
        long start, end;
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        start = System.currentTimeMillis();
        for (int k = 0; k < 100; k++) {// 每个线程接收消息数量
            consumer.receive();
        }
        end = System.currentTimeMillis();
        System.out.println("start time:" + start + "end time:" + end + " 接收消息耗时Run Time:" + (end - start) + "(ms)"
                + " 接收消息结束" + df1.format(new Date()));
        consumer.close();

    }

    public Session getSession() {
        Session session1 = null;
        InforsuiteMQConnectionFactory connectionFactory = new InforsuiteMQConnectionFactory(user, password, url);
        Connection connection;
        try {
            connection = connectionFactory.createConnection();
            connection.start();
            session1 = connection.createSession(false, ackMode);
        } catch (JMSException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return session1;
    }
}